package com.qf.demo3.Utils;

import com.qf.demo3.entity.Address;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

public class AddExcel {

    /**
     * 向Excel中追加内容
     * @param
     * @throws Exception
     */
    public static void addNew(List<Address> list,String filePath) throws Exception{

//        List<Address> list = new ArrayList<Address>();
//        list.add(new Address(4,"北京市","北京市","丰台区","六里桥街道","六里桥4号"));
//        list.add(new Address(5,"北京市","北京市","丰台区","六里桥街道","六里桥5号"));
//        list.add(new Address(6,"北京市","北京市","丰台区","六里桥街道","六里桥6号"));

        FileInputStream in = new FileInputStream(filePath);
        XSSFWorkbook workbook = new XSSFWorkbook(in);
        XSSFSheet sheet = workbook.getSheetAt(0);
        XSSFRow row=sheet.getRow(1);

        FileOutputStream out = new FileOutputStream(filePath);
        //从第二行开始追加列
        /*row=sheet.getRow(1);
        row.createCell(3).setCellValue("AAA");
        row.createCell(4).setCellValue("BBB");*/

        //追加列数据
//        for(int i=0;i<list.size();i++){
//            Address student = list.get(i);
//            row = sheet.getRow(i+1);
//            row.createCell(3).setCellValue(student.getAge());
//            row.createCell(4).setCellValue(student.getName());
//            row.createCell(5).setCellValue(student.getAddress());
//        }

        for (Address address : list){
            row=sheet.createRow((short)(sheet.getLastRowNum()+1)); //在现有行号后追加数据
            row.createCell(0).setCellValue(address.getProvince()); //设置第一个（从0开始）单元格的数据
            row.createCell(1).setCellValue(address.getCity()); //设置第二个（从0开始）单元格的数据
            row.createCell(2).setCellValue(address.getArea()); //设置第二个（从0开始）单元格的数据
            row.createCell(3).setCellValue(address.getStreet()); //设置第二个（从0开始）单元格的数据
            row.createCell(4).setCellValue(address.getAddress()); //设置第二个（从0开始）单元格的数据

        }
        //追加行数据


        try {
            out.flush();
            workbook.write(out);
            out.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
